package com.platform.server.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;

/**
 * 二维码
 * @author TangPC
 *
 */
public class QRCodeUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);

	private static final String CHARSET = "utf-8";


	/**
	 * 解析二维码
	 * 
	 * @param file
	 *            二维码图片
	 * @return
	 * @throws Exception
	 */
	public static String decode(URL url) throws Exception {
		BufferedImage image;
		image = ImageIO.read(url);
		if (image == null) {
			return null;
		}
		BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Result result;
		Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
		hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
		result = new MultiFormatReader().decode(bitmap, hints);
		String resultStr = result.getText();
		return resultStr;
	}

	/**
	 * 解析二维码
	 * 
	 * @param url
	 *            二维码图片地址
	 * @return
	 * @throws Exception
	 */
	public static String decode(String url) throws Exception {
		return QRCodeUtil.decode(new URL(url));
	}

	
	/**
	 * 生成单据二维码
	 * @param share_url 二维码的路径
	 * @param pathUrl 
	 * 				二维码存放路径
	 * @return
	 * @throws Exception
	 */
	public static File createBARCode(String share_url,String pathUrl) throws Exception{
		File file = null;
		try {
			file = new File(pathUrl);
			BarcodeFactory.encode(share_url, 300, 300, file);
			logger.debug(file.getPath());
		} catch (Exception e) {
			throw new Exception("生成二维码失败："+e);
		}
		return file;
	}
	
	/**
	 * 生成二维码
	 * @param share_url
	 * @param pathUrl 
	 * 				二维码存放路径
	 * @return
	 * @throws Exception
	 */
	public static File createBARCode(String share_url,String pathUrl, String fileName) throws Exception{
		File file = null;
		try {
			file = new File(pathUrl +"/"+ fileName);
			if(!file.exists()){
				file.mkdirs();
			}
			file = new File(pathUrl +"/"+ fileName);
			BarcodeFactory.encode(share_url, 300, 300, file);
			logger.debug(file.getPath());
		} catch (Exception e) {
			throw new Exception("生成二维码失败："+e);
		}
		return file;
	}

}
